import 'dart:convert';

import 'package:cloud_medicine/http/config.dart';
import 'package:cloud_medicine/components/util.dart';
import 'package:cloud_medicine/http/user_api.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';

class AlterPasswordPage extends StatefulWidget {
  @override
  _AlterPasswordPageState createState() => _AlterPasswordPageState();
}

class _AlterPasswordPageState extends State<AlterPasswordPage> {
  final RegExp regPassword = RegExp(r"^[A-Za-z0-9]{6,20}$");
  final TextEditingController oldPasswordController = TextEditingController();
  final TextEditingController newPasswordController = TextEditingController();
  final TextEditingController newAgainPasswordController =
      TextEditingController();
  List<int> _errorList = [];

  Widget _buildInputTextField(
    TextEditingController controller,
    String plactholder,
    int index,
  ) {
    return Container(
      padding: EdgeInsets.all(10),
      margin: EdgeInsets.only(top: 20),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border.all(color: Colors.grey[300], width: 1),
      ),
      child: TextField(
        controller: controller,
        maxLines: 1,
        obscureText: true,
        decoration: InputDecoration(
          contentPadding: EdgeInsets.symmetric(vertical: 10.0),
          border: OutlineInputBorder(
            borderSide: BorderSide.none,
          ),
          errorText: _errorList.contains(index) ? '请使用6~20位数字或字母作为密码' : null,
          hintText: plactholder,
          hintStyle: TextStyle(color: Colors.grey),
        ),
        onChanged: (String text) {
          // 如果验证为错，则向errorList中增加一个值，否则则去掉值
          if (!(regPassword.hasMatch(text))) {
            if(!_errorList.contains(index)) {
              setState(() {
                _errorList.add(index);
              });
            }
          }else{
            setState(() {
              _errorList.remove(index);
            });
          }
        },
      ),
    );
  }

  _alterPassword() async {
    if(_errorList.length != 0) {
      Fluttertoast.showToast(
        msg: '填入的密码有 ${_errorList.length}项 不符合规范，请修改之后再重试',
        gravity: ToastGravity.CENTER,
        backgroundColor: Colors.red,
        textColor: Colors.white,
      );
      return;
    }

    if(newAgainPasswordController.text != newPasswordController.text) {
      Fluttertoast.showToast(
        msg: '两次输入的密码不一致',
        gravity: ToastGravity.CENTER,
        backgroundColor: Colors.red,
        textColor: Colors.white,
      );
      return;
    }

    Response res = await alterPassword_api('$backIP/user/password', {
      'oldPassword': generateMd5(oldPasswordController.text),
      'newPassword': generateMd5(newPasswordController.text)
    });

    if(jsonDecode(res.data)['code'] == 0) {
      Fluttertoast.showToast(
        msg: jsonDecode(res.data)['message'],
        gravity: ToastGravity.TOP,
        backgroundColor: Colors.lightGreenAccent,
        textColor: Colors.white,
      );
      Navigator.pop(context);
    }else{
      errorToast(jsonDecode(res.data)['message']);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('修改密码'),
        centerTitle: true,
      ),
      body: ListView(
        children: <Widget>[
          _buildInputTextField(oldPasswordController, '请输入当前密码', 0),
          _buildInputTextField(newPasswordController, '请输入新密码', 1),
          _buildInputTextField(newAgainPasswordController, '请输入再输入一次新密码', 2),
          SizedBox(height: 20),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              RaisedButton(
                color: Colors.blue,
                textColor: Colors.white,
                onPressed: _alterPassword,
                child: Text('修改'),
              ),
            ],
          )
        ],
      ),
    );
  }
}
